package com.ruoyi.system.phone.controller;

import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.V2.goodInfo.service.IGoodsInfoService;
import com.ruoyi.system.model.domain.Finance;
import com.ruoyi.system.model.domain.GoodsInfo;
import com.ruoyi.system.phone.domain.TelManageNewImport;
import com.ruoyi.system.telMsg.domain.TelSendMsg;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.poi.openxml4j.util.ZipSecureFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.phone.domain.TelManageNew;
import com.ruoyi.system.phone.service.ITelManageNewService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 手机卡管理Controller
 *
 * @author ruoyi
 * @date 2024-12-05
 */
@RestController
@RequestMapping("/telManage")
public class TelManageNewController extends BaseController {
    @Autowired
    private ITelManageNewService telManageNewService;

    @Autowired
    private IGoodsInfoService goodsInfoService;

    /**
     * 查询手机卡管理列表
     */
    @GetMapping("/list")
    public TableDataInfo list(TelManageNew telManageNew) {
        if (!Objects.equals(getUserId(), 1L)) {
            Long deptId = getLoginUser().getUser().getDeptId();
            telManageNew.setDeptId(deptId);
            if (Objects.isNull(telManageNew.getIsUse())) {
                telManageNew.setIsUse(0);// 非管理员查看 只能看到未受限的
            }
        }
        startPage();
        List<TelManageNew> list = telManageNewService.selectTelManageNewList(telManageNew);
        if (CollectionUtils.isEmpty(list)) {
            return getDataTable(list);
        }
        builderParam(list);
        return getDataTable(list);
    }

    /**
     * 查询手机卡管理列表
     */
    @GetMapping("/listV1")
    public TableDataInfo listV1(TelManageNew telManageNew) {
        startPage();
        List<TelManageNew> list = telManageNewService.selectTelManageNewList(telManageNew);
        if (CollectionUtils.isEmpty(list)) {
            return getDataTable(list);
        }
        builderParam(list);
        return getDataTable(list);
    }

    /**
     * 查询游戏绑定详情
     *
     * @param list
     */
    public void builderParam(List<TelManageNew> list) {


        List<Long> collect = list.stream().map(s -> s.getId()).collect(Collectors.toList());

        GoodsInfo goodsInfo = new GoodsInfo();
        goodsInfo.setTelIds(collect);
        List<Map<String, Object>> maps = goodsInfoService.selectGoodsGameTotal(goodsInfo);
        Map<Long, List<Map<String, Object>>> listMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(maps)) {
            listMap = maps.stream().collect(Collectors.groupingBy(s -> MapUtils.getLong(s, "telid")));
        }

        for (TelManageNew manageNew : list) {
            JSONObject jsonData = new JSONObject();
            if (Objects.nonNull(manageNew.getUseEndTime())) {
                Integer day = (int) ((manageNew.getUseEndTime().getTime() - System.currentTimeMillis()) / 24 / 60 / 60 / 1000);
                if (day < 0) {
                    day = 0;
                }
                manageNew.setUseEndDay(day);
            }
            List<Map<String, Object>> mapList = listMap.get(manageNew.getId());
            // 如果空列表 直接跳过
            if (CollectionUtils.isNotEmpty(mapList)) {
                for (Map<String, Object> map : mapList) {

                    String gameType = MapUtils.getString(map, "gameType");
                    Integer sum = MapUtils.getInteger(map, "sum");
                    String gameData = MapUtils.getString(map, "gameData");

                    List<JSONObject> dataList = new ArrayList<>();
                    // 如果空列表 直接跳过
                    if (StringUtils.isNotEmpty(gameData)) {
                        String[] split = gameData.split(",");
                        for (String s : split) {
                            JSONObject value = new JSONObject();
                            String[] split1 = s.split(":");
                            value.put("key", split1[0]);
                            value.put("carrier", split1[1]);
                            value.put("value", split1[2]);
                            dataList.add(value);
                        }
                    }
                    // 如果空列表 直接跳过
                    if (CollectionUtils.isEmpty(dataList)) {
                        continue;
                    }
                    JSONObject data = new JSONObject();
                    data.put("count", sum);
                    data.put("dataList", dataList);
                    if (StringUtils.equals(gameType, "腾讯")) {
                        {
                            JSONObject qqData = new JSONObject();
                            List<JSONObject> qqLIST = dataList.stream().filter(s -> s.getString("carrier").contains("QQ") || !s.getString("carrier").contains("微信")).collect(Collectors.toList());

                            qqData.put("count", qqLIST.size());
                            qqData.put("dataList", qqLIST);
                            if (qqLIST.size() > 0) {
                                jsonData.put("qq", qqData);
                            }
                        }
                        {
                            JSONObject wxData = new JSONObject();
                            List<JSONObject> wxLIST = dataList.stream().filter(s -> !s.getString("carrier").contains("QQ") && s.getString("carrier").contains("微信")).collect(Collectors.toList());
                            wxData.put("count", wxLIST.size());
                            wxData.put("dataList", wxLIST);
                            if (wxLIST.size() > 0) {
                                jsonData.put("wx", wxData);
                            }
                        }
                    }
                    if (StringUtils.equals(gameType, "网易")) {
                        jsonData.put("wy", data);
                    }
                    if (StringUtils.equals(gameType, "米哈游")) {
                        jsonData.put("mhy", data);
                    }
                    if (StringUtils.equals(gameType, "库洛")) {
                        jsonData.put("kl", data);
                    }
                }
            }
            manageNew.setBindData(jsonData);
        }
    }

    /**
     * 导出手机卡管理列表
     */
    @GetMapping("/export")
    public AjaxResult export(TelManageNew telManageNew) {
        List<TelManageNew> list = telManageNewService.selectTelManageNewList(telManageNew);
        ExcelUtil<TelManageNew> util = new ExcelUtil<TelManageNew>(TelManageNew.class);
        return util.exportExcel(list, "手机卡管理数据");
    }

    /**
     * 导出手机卡管理列表
     */
    @GetMapping("/getImportExcel")
    public AjaxResult getImportExcel() {
        ExcelUtil<TelManageNewImport> util = new ExcelUtil<TelManageNewImport>(TelManageNewImport.class);
        List<TelManageNewImport> list = new ArrayList<>();
        TelManageNewImport newImport = new TelManageNewImport();
        newImport.setTel("12345678910");
        newImport.setNum("小米1");
        newImport.setCustodianType("企业卡/公司卡/个人卡");
        newImport.setCustodian("实名人");
        newImport.setCategory("天空/虞都");
        newImport.setCarrier("联通/电信/移动/广电");
        newImport.setRemark("备注");
        list.add(newImport);
        return util.exportExcel(list, "手机卡导入模板");
    }


    @Log(title = "手机卡导入", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception {
        ExcelUtil<TelManageNew> util = new ExcelUtil<TelManageNew>(TelManageNew.class);
        ZipSecureFile.setMinInflateRatio(-1.0d);
        List<TelManageNew> list = util.importExcel(file.getInputStream());
        String message = telManageNewService.bathInsert(list);
        return AjaxResult.success(message);
    }

    /**
     * 获取手机卡管理详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(telManageNewService.selectTelManageNewById(id));
    }

    /**
     * 新增手机卡管理
     */
    @PostMapping
    public AjaxResult add(@RequestBody TelManageNew telManageNew) {
        if (Objects.isNull(telManageNew.getDeptId())) {
            throw new GlobalException("部门不可为空");
        }
        telManageNew.setCreateId(SecurityUtils.getUserId());
        return toAjax(telManageNewService.insertTelManageNew(telManageNew));
    }

    /**
     * 修改手机卡管理
     */
    @PutMapping
    public AjaxResult edit(@RequestBody TelManageNew telManageNew) {
        telManageNew.setUpdateId(SecurityUtils.getUserId());
        return toAjax(telManageNewService.updateTelManageNew(telManageNew));
    }


    /**
     * 恢复使用状态
     */
    @GetMapping("/use/{id}")
    public AjaxResult use(@PathVariable("id") Long id) {
        telManageNewService.use(id);
        return AjaxResult.success();
    }

    /**
     * 发送短信
     */
    @PutMapping("sendSMS")
    public JSONObject sendSMS(@RequestBody TelSendMsg req) {
        return telManageNewService.sendSMS(req);
    }

    /**
     * 删除手机卡管理
     */
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(telManageNewService.deleteTelManageNewByIds(ids));
    }


    /**
     * 使用状态修改
     * isUser;手机类型  是否可以使用 0 可用  1 不可用
     * useType; 手机类型   0 默认  1 已使用  2 已频繁
     * useTime; 时间  7 ，15 ，30
     */
    @PostMapping("/userStatus")
    public AjaxResult userStatus(@RequestBody TelManageNew telManage) {
        telManageNewService.userStatus(telManage);
        return AjaxResult.success();
    }

}
